﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

//Needed to get the FormsAuthenticationTicket
using System.Web.Security;
using UNDP_Projects.Data_Access;
using UNDP_Projects.Classes;

using System.DirectoryServices;

namespace UNDP_Projects.Account
{
    public partial class WinLogin : Security
    {

        UNDPEntities db = new UNDPEntities();

        protected void Page_Load(object sender, EventArgs e)
        {
            using (DirectoryEntry de = new DirectoryEntry("LDAP://so.undp.local"))
            {
                using (DirectorySearcher adSearch = new DirectorySearcher(de))
                {

                    char[] separator = new char[] { '\\' };
                    string[] uName = User.Identity.Name.Split(separator);

                    adSearch.Filter = "(sAMAccountName=" + uName[1] + ")";
                    adSearch.PropertiesToLoad.Add("userPrincipalName");
                    SearchResult result = adSearch.FindOne();

                    DirectoryEntry dResult = result.GetDirectoryEntry();

                    string UserName = dResult.Properties["sAMAccountName"][0].ToString();


                    //==================================================================================
                    if (ValidateUser(UserName))
                    {
                        string roles;

                        string uEmail = UserName+"@undp.org";
                        //string uPword = base64Encode(Password.Text.Trim());
                        FormsAuthentication.Initialize();

                        try
                        {
                            var userRole = (from data in db.users
                                            where
                                                data.user_email == uEmail //&&
                                                //data.password == uPword
                                            select new
                                            {
                                                data.roles,
                                                data.active
                                            }).FirstOrDefault();

                            if (userRole.active == false)
                            {
                                Error.Visible = true;
                                Error.Text = "Sorry you have been deactivated. Please contact the system administrator.";
                                return;
                            }

                            roles = userRole.roles.Trim();

                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Login Error " + ex.Message + " " + ex.StackTrace);
                            //Label2.Text = "Login Error " + ex.Message + " " + ex.StackTrace;
                        }
                        FormsAuthenticationTicket ticket;
                        string hashedCookieString;
                        HttpCookie cookie;

                        //Create a new ticket used for authentication
                        ticket = new FormsAuthenticationTicket(
                            1, //Ticket version
                            uEmail.Trim(), //Username associated with the ticket
                            DateTime.Now, //Date issued
                            DateTime.Now.AddMinutes(60), //Date/Time to expire
                            true, //Persistant User cookie
                            roles, //Custom data i.e user role
                            FormsAuthentication.FormsCookiePath //Path for the ticket when stored in a cookie
                            );

                        //Encrypt the cookie using the machine key for secure transport
                        hashedCookieString = FormsAuthentication.Encrypt(ticket);

                        cookie = new HttpCookie(
                            FormsAuthentication.FormsCookieName, //Name of authentication cookie
                            hashedCookieString //Encrypted ticket
                            );

                        // Set the cookie's expiration time to the tickets expiration time
                        //if (PersistCookie.Checked)
                        //{
                            cookie.Expires = ticket.Expiration;
                        //}

                        // Add the cookie to the list for outgoing response
                        Response.Cookies.Add(cookie);

                        //Record the Login date for the user
                        user logginInUser = db.users.FirstOrDefault(
                                                    data => data.user_email == uEmail);
                        if (logginInUser != null)
                        {
                            logginInUser.login_date = DateTime.Now.ToString();
                            db.SaveChanges();
                        }


                        // Redirect to requested URL, or homepage if no previous page requested
                        //string returnURL = Request.QueryString["ReturnUrl"].Trim();
                        if (string.IsNullOrEmpty(Request["ReturnUrl"]))
                        {
                            Response.Redirect("~/Home.aspx");
                        }
                        Response.Redirect(Request.QueryString["ReturnUrl"].Trim(), true);
                        //Response.Redirect(FormsAuthentication.GetRedirectUrl(uEmail,true));

                    }
                    else
                    {
                        Error.Visible = true;
                        Error.Text = "Provide your correct credentials";
                    }
                    //=============================================================================
                }
            }
        }

        private bool ValidateUser(string UName)
        {
            string enteredPassword = null;
            string UNameAddress = UName + "@undp.org";

            try
            {
                string pWord = (from data in db.users
                                where
                                    data.user_email == UNameAddress
                                select data.password).FirstOrDefault();

                enteredPassword = base64Decode(pWord);
                return true;
            }
            catch (Exception ex)
            {
                //throw new Exception("Login Error "+ex.Message+" "+ex.StackTrace);
                Error.Visible = true;
                Error.Text = "You do not have access to this system " + ex.Message;
                Response.Redirect("~/Account/Login.aspx");
            }

            // If no password found, return false.
            //if (enteredPassword == null)
            //{
                // You could write failed login attempts here to event log for additional security.
                return false;
            //}

            // Compare enteredpassword and input passWord, using a case-sensitive comparison.
            //return (0 == string.Compare(enteredPassword, passWord, false));
        }

        //protected override void OnPreRender(EventArgs e)
        //{
        //    base.OnPreRender(e);

        //    string userName = Request.ServerVariables["LOGON_USER"];
        //    if (userName != null && userName.Length > 0)
        //    {
        //        GenericIdentity id = new GenericIdentity(userName);

        //        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
        //            1,
        //            userName,
        //            DateTime.Now,
        //            DateTime.Now.AddMinutes(60),
        //            false,
        //            Guid.NewGuid().ToString());

        //        string hashedCookieString = FormsAuthentication.Encrypt(ticket);

        //        HttpCookie cookie = new HttpCookie(
        //            FormsAuthentication.FormsCookieName, //Name of authentication cookie
        //            hashedCookieString //Encrypted ticket
        //            );

        //        HttpContext.Current.Response.Cookies.Add(cookie);
        //    }
        //    else
        //    {
        //        Response.Redirect("~/Account/Login.aspx");
        //    }
        //}
    }
}